<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="更改日期" prop="create_time"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 状态修改 -->
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 删除 分配 -->

            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-share"
                @click="setUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 主题内容区域 -->

        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button @click="addUser" type="primary">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="50%">
        <!-- 修改的内容区域 -->

        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="80px"
        >
        <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserinfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色分配对话框 -->

      <el-dialog title="角色分配" :visible.sync="UserShowPower" width="60%">
        <p>用户名：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>

        <el-select v-model="overUserId" placeholder="请选择">
          <el-option
            v-for="item in reloesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <span slot="footer" class="dialog-footer">
          <el-button @click="UserShowPower = false">取 消</el-button>
          <el-button type="primary" @click="setUserPower">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱格式不正确'))
    }

    var checkMobile = (rule, value, cb) => {
      const regMobile =
        
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('手机格式不正确'))
    }
    return {
      // 用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1, //当前页数
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示隐藏
      addDialogVisible: false,
      //控制分配角色对话框显示隐藏
      UserShowPower: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 表单验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名：',
            trigger: 'blur',
          },
          { min: 3, max: 5, message: '用户名长度3--5位', trigger: 'blur' },
        ],
        password: [
          {
            required: true,
            message: '密码',
            trigger: 'blur',
          },
          { min: 3, max: 16, message: '密码长度3--16位', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },

          { validator: checkEmail, trigger: 'blur,change' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },

          { validator: checkMobile, trigger: 'blur,change' },
        ],
      },
      //修改用户表单验证
       editFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur,change' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur,change' },
        ],
      },
      //控制修改用户对话框
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      //表中的角色的信息
      userInfo: '',
      //角色列表
      reloesList: [],
      //已经选中的角色的ID
      overUserId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      console.log(res)
      if (res.meta.status != 200) return this.$message.error('获取数据失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize分页
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },

    //  :current-page="currentPage4" 当前显示的第几页
    //监听页码值
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    //状态修改
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更改失败')
      }
      this.$message.success('更改成功')
    },
    //退出清空
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res.meta.status)
        if (res.meta.status != 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')

        // 隐藏对话框 渲染数据
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    //获取修改的用户信息
    async showEditDialog(id) {
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)

      //成功 先保存到data
      this.editForm = res.data

      // 控制修改对话框显示
      this.editDialogVisible = true
    },
    // 修改数据方法
    editUserinfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) return

        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )

        if (res.meta.status != 200) return this.$message.error('更新失败！')

        this.getUserList()
        this.editDialogVisible = false

        this.$message.success('更新成功')
      })
    },
    //删除用户
    async removeUserById(id) {
      console.log(id)
      const confirmrsult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果确认删除 confirm
      //取消 cancel
      console.log(confirmrsult)
      if (confirmrsult != 'confirm') return this.$message.info('已经取消删除')

      const { data: res } = await this.$http.delete('users/' + id)

      if (res.meta.status != 200) return this.$message.error('删除失败')

      this.$message.success('删除成功！')

      this.getUserList()
    },
    //获取到原始角色
    async setUser(userInfo) {
      this.userInfo = userInfo
      this.UserShowPower = true

      const { data: res } = await this.$http.get('roles')
      this.reloesList = res.data
    },
    //角色分配
    async setUserPower() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.overUserId }
      )
      if (res.meta.status != 200) return this.$message.error('分配角色失败')

      this.$message.success('分配角色成功！')
      console.log(this.overUserId)
      this.getUserList()
      this.UserShowPower = false
    },
  },
}
</script>
<style>
</style>